/*
 * ProfileManager.java
 *
 * Created on March 13, 2007, 8:24 PM
 */

package d20chat;

import java.io.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.*;       // Used for JFileChooser
import javax.swing.JList;
import javax.swing.JOptionPane;
import java.awt.*;


/**
 * Allows a user to manager profiles.
 * (create, edit, delete, import, export, set a default, load default profile at 
 * program startup, and load a profile to be used in the current session.
 */
public class ProfileManager extends javax.swing.JFrame {
    
    //private Client tempclient;
    /**
     * Used to access if profiles should be loaded up on default.
     */
    public D20Chat tempMain;
    //public d20chatui tempGui;
    //private OutgoingMessageParser OutParse;
    //private Server tempserver;
    //private User thisUser;
    private JFileChooser fc = new JFileChooser();
    private JList pList;
    /**
     * directory that profiles are stored in.
     */
    public String profileDir = "profiles/";
    /**
     * Path to get to the profiles.
     */
    public String profilePath = profileDir + "profileList.txt";
    private String defaultProfile = "";
    private String settingsFile = profileDir + "settings.txt";
    private boolean loadDefaultOnStartup = false;
    private JFrame frame = new JFrame();

    
/**
     * Class constructor for ProfileManager.
     * Sets up the window, as well as loads information from the profile files.
     */
    public ProfileManager() {
        initComponents();
        
        // Center Profile Manager jFrame
        Dimension scrn = getToolkit().getScreenSize();
        this.setBounds( (scrn.width-getWidth())/2, (scrn.height-getHeight())/2, getWidth(), getHeight() );
        
        // Create a file filter for the JFile Chooser (save profile as .txt)
        FileFilter filter = new FileNameExtensionFilter("Text File (.txt)", "txt");
        fc.addChoosableFileFilter(filter);
        
        // Make sure profile directory and file exists (create if not)
        try {
            boolean profileDirExists = (new File("profiles")).exists();
            if (!profileDirExists) {
                // Profile Directory does NOT exist
                // Create profile directory AND file
                boolean success = (new File("profiles")).mkdir();

                // Create file since it does not exist
                //  (directory didn't so file won't)
                File file = new File(profilePath);
                success = file.createNewFile();
            } else {
                // Profile diretory does exist, check if file exists
                boolean profileFileExists = (new File(profilePath)).exists();
                if (!profileFileExists) {
                    // Profile list file does not exist, so create it
                    File file = new File(profilePath);
                    boolean success = file.createNewFile();
                }
            }
        } catch (Exception e) {
            System.out.println("Could not create profile directory or file!");
        }
        
        // Load in "Imported" profiles (profiles that D20 Chat knows about)
        // Read profile from file
        try {
            // Create a buffer for our file to read into
            BufferedReader bin = new BufferedReader(new FileReader(profilePath));
            
            // Read in profile(s) and add to profile listing
            String profileName = bin.readLine();
            DefaultListModel listModel = new DefaultListModel();
            while (profileName != null) {
                // Check if profile is currently being used and indicate so
                //if (tempMain.theUser.getUsername().compareTo("") != 0)
                //    if (profileName.compareTo(tempMain.theUser.getUsername().toString()) == 0)
                //        profileName = profileName + "   [LOADED]";
                
                // Add profile to temporary list listModel
                listModel.addElement(profileName);
                
                // Read in next profileName
                profileName = bin.readLine();
            }

            // Make jList a single selection jList and list of
            //  profiles to profileList scrollpane
            pList = new JList(listModel);
            pList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            this.profileList.setViewportView(pList);

            bin.close();
        }
        catch (Exception e) {
                System.err.println ("Error reading file " + profilePath);
        }
        
        // If loadDefaultOnStartup is enabled then check the checkbox too
        this.loadDefault.setSelected(loadDefaultOnStartup);
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        lblExplanation = new javax.swing.JLabel();
        loadDefault = new javax.swing.JCheckBox();
        useProfile = new javax.swing.JButton();
        newProfile = new javax.swing.JButton();
        editProfile = new javax.swing.JButton();
        deleteProfile = new javax.swing.JButton();
        importProfile = new javax.swing.JButton();
        exportProfile = new javax.swing.JButton();
        profileList = new javax.swing.JScrollPane();
        setAsDefault = new javax.swing.JButton();
        cancel = new javax.swing.JButton();

        setTitle(" Profile Manager");
        setName("Profile Manager");
        setResizable(false);
        lblExplanation.setText("Select a profile:");

        loadDefault.setText("Load default on program startup");
        loadDefault.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        loadDefault.setMargin(new java.awt.Insets(0, 0, 0, 0));
        loadDefault.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                loadDefaultItemStateChanged(evt);
            }
        });

        useProfile.setText("Use Profile");
        useProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                useProfileActionPerformed(evt);
            }
        });

        newProfile.setText("New");
        newProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newProfileActionPerformed(evt);
            }
        });

        editProfile.setText("Edit");
        editProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editProfileActionPerformed(evt);
            }
        });

        deleteProfile.setText("Delete");
        deleteProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteProfileActionPerformed(evt);
            }
        });

        importProfile.setText("Import");
        importProfile.setMaximumSize(new java.awt.Dimension(63, 23));
        importProfile.setMinimumSize(new java.awt.Dimension(63, 23));
        importProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importProfileActionPerformed(evt);
            }
        });

        exportProfile.setText("Export");
        exportProfile.setMaximumSize(new java.awt.Dimension(63, 23));
        exportProfile.setMinimumSize(new java.awt.Dimension(63, 23));
        exportProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportProfileActionPerformed(evt);
            }
        });

        setAsDefault.setText("Set as Default");
        setAsDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setAsDefaultActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblExplanation)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(profileList, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                            .addComponent(setAsDefault, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                            .addComponent(loadDefault))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(exportProfile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(importProfile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(editProfile, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)
                                            .addComponent(newProfile, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addComponent(deleteProfile, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(useProfile, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 132, Short.MAX_VALUE)
                        .addComponent(cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblExplanation)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(newProfile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editProfile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteProfile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(importProfile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(profileList, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setAsDefault)
                    .addComponent(exportProfile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(loadDefault)
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancel)
                    .addComponent(useProfile))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    
/********************************************************************************
  Method: cancelActionPerformed
  Description: Cancel button action for the profile manager window
  Parameters: evt
  Used by: ProfileManager.java
  Uses: NONE
********************************************************************************/
    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
// Hide form
        this.setVisible(false);
    }//GEN-LAST:event_cancelActionPerformed

    
/********************************************************************************
  Method: satAsDefaultActionPerformed
  Description: Allows the user to set the currently selected profile as default
  Parameters: evt
  Used by: ProfileManager.java
  Uses: saveProfileManagerSettings
********************************************************************************/
    private void setAsDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setAsDefaultActionPerformed
        // Set selected profile as default
        // Make sure that there is one selected
        if (!this.pList.isSelectionEmpty()) {
            // Get selected profile and set as default profile
            defaultProfile = this.getSelectedProfile();
        } else {
            // Set default profile to ""
            defaultProfile = "";
        }
        
        // Save the profile manager settings to file
        this.saveProfileManagerSettings();
    }//GEN-LAST:event_setAsDefaultActionPerformed

    
/********************************************************************************
  Method: loadDefaultItemStateChanged
  Description: Saves the load default on program startup option when changed
  Parameters: evt
  Used by: ProfileManager.java
  Uses: saveProfileManagerSettings
********************************************************************************/
    private void loadDefaultItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_loadDefaultItemStateChanged
        // Save whether to load default profile on startup
        if (loadDefault.isSelected())
            loadDefaultOnStartup = true;
        else
            loadDefaultOnStartup = false;
        
        this.saveProfileManagerSettings();
    }//GEN-LAST:event_loadDefaultItemStateChanged

    
/**
     * Saves all the profile manager settings to file.
     * (default profile and whether to load it on startup)
     *  Used by: setAsDefaultActionPerformed, loadDefaultItemStateChanged,
     *           loadDefaultProfile
     */
    private void saveProfileManagerSettings() 
    {
        // Save Profile Manager settings to settings file
        try {
            // Create a new file output stream
            //  connected to "saveLocation" path
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
        
            out = new FileOutputStream(settingsFile);

            // Connect print stream to the output stream
            p = new PrintStream(out);

            // Write default profile and default load settings to settings file
            p.println(defaultProfile);
            p.println(loadDefaultOnStartup);

            p.close();
        }
        catch (Exception e)
        {
            System.err.println ("Unable to write to file:\n\t" + settingsFile + "!");
        }
    }

    
/**
     * Loads in the default profile settings (profile and load on startup).
     * @return returns fals if there is no profile to load
     */
    public boolean loadDefaultProfile() 
    {
        try {
            File settings = new File(settingsFile);
            
            if (settings.length() > 0) {
                // Create a buffer for our file to read into
                BufferedReader bin = new BufferedReader(new FileReader(settingsFile));
                
                // Read in default profile and store in current profile
                defaultProfile = bin.readLine();
                String strLoadDefault = bin.readLine();
                
                // Convert the string "true/false" to boolean true/false
                loadDefaultOnStartup = Boolean.parseBoolean(strLoadDefault);
                
                tempMain.loadDefaultProfile = loadDefaultOnStartup;

                bin.close();
            }
        } catch (Exception e) {
            System.err.println("Attempting to load default profile.");
        }
        
        // If there is no profile to load, return false
        // Otherwise, there is (and it has been stored) so return true
        if (loadDefaultOnStartup == false)
            return false;
        else {
            // Check to make sure default profile file exists
            //  (make sure it hasn't been deleted)
            boolean profileFileExists = (new File(profilePath)).exists();
            if (profileFileExists) {
                // Read in entire profile and load in as current profile
                String defaultProfilePath = profileDir + defaultProfile + ".txt";

                String readUsername = "";
                String readName = "";
                String readEmail = "";
                String readPhone = "";
                String readWebsite = "";
                String readAboutMe = "";
                String readVisible = "";

                // Read profile from file
                try {
                    // Create a buffer for our file to read into
                    BufferedReader bin = new BufferedReader(new FileReader(defaultProfilePath));

                    // Read in profile and store for use to export
                    readUsername = bin.readLine();
                    readName = bin.readLine();
                    readEmail = bin.readLine();
                    readPhone = bin.readLine();
                    readWebsite = bin.readLine();
                    readAboutMe = bin.readLine();
                    readVisible = bin.readLine();

                    boolean visible = false;
                    visible = Boolean.parseBoolean(readVisible);

                    // Set the user info
                    tempMain.theUser.userProfile.setProfile(readName, readEmail, readAboutMe, readWebsite, readPhone, visible);
                    tempMain.theUser.setUsername(readUsername);

                    bin.close();
                }
                catch (Exception e) {
                    System.err.println("Could not read profile: " + readUsername);
                }

                return true;
            } else {
                defaultProfile = "";
                loadDefaultOnStartup = false;
                
                // Save that there is no default profile to load on startup
                //  (since the previous profile to load on startup does
                //   not exist)
                this.saveProfileManagerSettings();
                
                return false;
            }
        }
    }
    
    
/**
     * Startup method to perform startup tasks for the profile manager.
     */
    private void startup() {
        // This function will display the Profile Manager according to user
        //  defined preferences (the "Load default profile on startup" option)

        // If this setting is set then the default profile will be loaded on
        //  startup and the Profile Manager will not be displayed, otherwise it
        //  will be displayed at program startup
        if (!loadDefaultOnStartup)
            this.setVisible(true);
    }
    
    
/********************************************************************************
  Method: importProfileActionPerformed
  Description: Allows a user to import a profile into D20 Chat
  Parameters: evt
  Used by: ProfileManager.java
  Uses: NONE
********************************************************************************/
    private void importProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importProfileActionPerformed
        // Display open dialog window to open profile from file
        int returnVal = fc.showOpenDialog(this);

        // Setup temporary storage for imported profile
        String readUsername = "";
        String readName = "";
        String readEmail = "";
        String readPhone = "";
        String readWebsite = "";
        String readAboutMe = "";
        String readVisible = "";

        // User saved the profile to file
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File openedFile = fc.getSelectedFile();
            String openLocation = openedFile.getPath();

            // Read in profile to save to project directory profile file
            //  and add to pList profile jList
            try {
                // Create a buffer for our file to read into
                BufferedReader bin = new BufferedReader(new FileReader(openLocation));

                // Read in profile(s) and add to profile listing
                readUsername = bin.readLine();
                readName = bin.readLine();
                readEmail = bin.readLine();
                readPhone = bin.readLine();
                readWebsite = bin.readLine();
                readAboutMe = bin.readLine();
                readVisible = bin.readLine();

                // Done reading profile from file, so close file
                bin.close();
            } catch (Exception e) {
                    System.err.println ("Error reading file");
            }

            // Add profile to jList, write to profile list file,
            //  and check if it's a duplicate (if duplicate don't add)
            try {
                // Check if profile (username) is already added
                // Create a buffer for our file to read into
                BufferedReader bin = new BufferedReader(new FileReader(profilePath));

                // Setup to check if new profile already exists
                boolean profileAdded = false;            
                String line = bin.readLine();
                while (line != null) {
                    // Check if currently read in profile is same as
                    //  currently added profile
                    if (line.compareTo(readUsername) == 0)
                        profileAdded = true;

                    // Read in next profile
                    line = bin.readLine();
                }

                // Append new profile if profile is NOT currently in list to
                //  profile list file
                // If profile does already exist then just leave list alone
                //  (it's already in there so no need to add it or remove it)
                if (profileAdded) {
                    // Tell user that this profile is already in list
                    // Ask if they would like to overwrite or not
                    String message = "The profile " + readUsername;
                    message = message + " is already being used.\n";
                    message = message + "Do you wish to overwrite it?";
                    int overwrite = JOptionPane.showOptionDialog(frame, message, "Import Profile", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);

                    if (overwrite == JOptionPane.YES_OPTION) {
                        // Create a new file output stream connected
                        //  to "profilePath" path
                        FileOutputStream out; // declare a file output object
                        PrintStream p; // declare a print stream object
                    
                        // Save profile in project directory
                        String saveLocation = profileDir + readUsername + ".txt";

                        // Create a new file output stream
                        //  connected to "saveLocation" path
                        out = new FileOutputStream(saveLocation);

                        // Connect print stream to the output stream
                        p = new PrintStream(out);

                        // Write profile information to file
                        p.println (readUsername);
                        p.println (readName);
                        p.println (readEmail);
                        p.println (readPhone);
                        p.println (readWebsite);
                        p.println (readAboutMe);
                        p.println (readVisible);

                        p.close();

                        // Either profile has been found or added
                        // Done using file, so close it
                        bin.close();
                    }
                } else {
                    // Create a new file output stream connected
                    //  to "profilePath" path
                    FileOutputStream out; // declare a file output object
                    PrintStream p; // declare a print stream object

                    out = new FileOutputStream(profilePath, true);

                    // Connect print stream to the output stream
                    p = new PrintStream(out);

                    // Write profile to profileList
                    p.println (readUsername);

                    p.close();
                    
                    // Save profile in project directory
                    String saveLocation = profileDir + readUsername + ".txt";

                    // Create a new file output stream
                    //  connected to "saveLocation" path
                    out = new FileOutputStream(saveLocation);

                    // Connect print stream to the output stream
                    p = new PrintStream(out);

                    // Write profile information to file
                    p.println (readUsername);
                    p.println (readName);
                    p.println (readEmail);
                    p.println (readPhone);
                    p.println (readWebsite);
                    p.println (readAboutMe);
                    p.println (readVisible);

                    p.close();

                    // Read in profile(s) already in pList (
                    DefaultListModel listModel = new DefaultListModel();
                    for (int i=0; i<pList.getModel().getSize(); i++)
                        listModel.addElement(pList.getModel().getElementAt(i).toString());

                    // Add profile to temporary list listModel
                    listModel.addElement(readUsername);

                    // Make jList a single selection jList and list of
                    //  profiles to profileList scrollpane
                    pList = new JList(listModel);
                    pList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                    this.profileList.setViewportView(pList);

                    // Either profile has been found or added
                    // Done using file, so close it
                    bin.close();
                }
            } catch (Exception e) {
                System.err.println ("Unable to write profile to file!");
            }
        }
    }//GEN-LAST:event_importProfileActionPerformed

    
/********************************************************************************
  Method: deleteProfileActionPerformed
  Description: Allows a user to delete a profile from the profile manager
  Parameters: evt
  Used by: ProfileManager.java
  Uses: removeProfile
********************************************************************************/
    private void deleteProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteProfileActionPerformed
        // Check to make sure a profile has been selected in the jList
        if (pList.isSelectionEmpty())
            JOptionPane.showMessageDialog(frame, "Please select a profile to delete.", "Profile Manager", JOptionPane.WARNING_MESSAGE);
        else {
            // Get the selected profile
            String profile = this.getSelectedProfile();

            // Ask user if they're sure they want to delete the profile
            String message = "Are you sure you want to delete profile ";
            message = message + profile + "?";
            int result = JOptionPane.showOptionDialog(frame, message, "Delete Profile", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);
            
            if (result == JOptionPane.YES_OPTION) // Remove selected profile
                this.removeProfile(profile);
        }
    }//GEN-LAST:event_deleteProfileActionPerformed

    
/********************************************************************************
  Method: editProfileActionPerformed
  Description: Allows a user to edit a profile already loaded into D20 Chat
               (whether created on the local machine or imported in)
  Parameters: evt
  Used by: ProfileManager.java
  Uses: EditProfile.java
********************************************************************************/
    private void editProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editProfileActionPerformed
        // Check to make sure a profile has been selected in the jList
        if (pList.isSelectionEmpty())
            JOptionPane.showMessageDialog(frame, "Please select a profile to edit.", "Profile Manager", JOptionPane.WARNING_MESSAGE);
        else {
            // Show "Create New Profile" window to create a new profile
            EditProfile editProfile;
            editProfile = new EditProfile();
            //editProfile.tempMain = tempMain;
            editProfile.profileManager = this;

            editProfile.setVisible(true);
        }
    }//GEN-LAST:event_editProfileActionPerformed

    
/********************************************************************************
  Method: useProfileActionPerformed
  Description: Loads a selected profile in the profile manager to be used in the
               current session
  Parameters: evt
  Used by: ProfileManager.java
  Uses: indicateUsedProfile
********************************************************************************/
    private void useProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useProfileActionPerformed
    String info;
        
        // Check to make sure a profile has been selected in the jList
        if (pList.isSelectionEmpty())
            JOptionPane.showMessageDialog(frame, "Please select a profile to use.", "Profile Manager", JOptionPane.WARNING_MESSAGE);
        else {
            // Get selected profile then load into current user
            String selectedProfile = this.getSelectedProfile();
        
            // Set selected profile font to bold to indicate it is being used
            this.indicateUsedProfile();

            // Read in entire profile and load in as current profile
            String selectedProfilePath = profileDir + selectedProfile + ".txt";

            String readUsername = "";
            String readName = "";
            String readEmail = "";
            String readPhone = "";
            String readWebsite = "";
            String readAboutMe = "";
            String readVisible = "";

            // Read profile from file
            try {
                // Create a buffer for our file to read into
                BufferedReader bin = new BufferedReader(new FileReader(selectedProfilePath));

                // Read in profile and store for use to load as current user
                readUsername = bin.readLine();
                readName = bin.readLine();
                readEmail = bin.readLine();
                readPhone = bin.readLine();
                readWebsite = bin.readLine();
                readAboutMe = bin.readLine();
                readVisible = bin.readLine();

                Boolean visible = false;
                visible = Boolean.parseBoolean(readVisible);

                // Store in current profile
                tempMain.theUser.userProfile.setProfile(readName, readEmail, readAboutMe, readWebsite, readPhone, visible);
                tempMain.theUser.setUsername(selectedProfile);
                
                //let the server know info has been updated
                if( tempMain.connected == true )
                {
                    if( tempMain.theUser.userProfile.getVisible() == true )
                    {
                        info = "/userInfo " + tempMain.theUser.toString();
                        tempMain.OutParse.sendMessage( info );
                    }
                    else
                    {
                        info = "/changeName " + tempMain.theUser.getUsername();
                        tempMain.OutParse.sendMessage( info );
                        info = "/hideProfile ";
                        tempMain.OutParse.sendMessage( info );
                    }
                }

                bin.close();
            }
            catch (Exception e)
            {
                    System.err.println ("Error reading file: " + selectedProfilePath);
            }

            this.setVisible(false);
        }
    }//GEN-LAST:event_useProfileActionPerformed

    
/********************************************************************************
  Method: exportProfileActionPerformed
  Description: Allows a user to export the selected profile to file
  Parameters: evt
  Used by: ProfileManager.java
  Uses: NONE
********************************************************************************/
    private void exportProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportProfileActionPerformed
        // Check to make sure a profile has been selected in the jList
        if (pList.isSelectionEmpty())
            JOptionPane.showMessageDialog(frame, "Please select a profile to export.", "Profile Manager", JOptionPane.WARNING_MESSAGE);
        else {
            // Get selected profile username then read it's file
            //  and load into memory to write to user selected file

            // Get the index of the selected profile
            int selectedIndex = pList.getSelectedIndex();

            // Get the selected profile using the index
            Object selectedProfile = pList.getModel().getElementAt(selectedIndex);

            // Get the profile name
            String username = selectedProfile.toString();

            // Build profile path
            String filePath = profileDir + username + ".txt";

            // Create temporary profile to store for export use
            String readUsername = "";
            String readName = "";
            String readEmail = "";
            String readPhone = "";
            String readWebsite = "";
            String readAboutMe = "";
            String readVisible = "";

            // Read profile from file
            try {
                // Create a buffer for our file to read into
                BufferedReader bin = new BufferedReader(new FileReader(filePath));

                // Read in profile and store for use to export
                readUsername = bin.readLine();
                readName = bin.readLine();
                readEmail = bin.readLine();
                readPhone = bin.readLine();
                readWebsite = bin.readLine();
                readAboutMe = bin.readLine();
                readVisible = bin.readLine();

                bin.close();
            }
            catch (Exception e)
            {
                    System.err.println ("Error reading file");
            }

            // Display save dialog window to save profile to file
            int returnVal = fc.showSaveDialog(this);

            // User saved the profile to file
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File savedFile = fc.getSelectedFile();
                String saveLocation = savedFile.getPath();

                // Append the ".txt" extension if user does not supply it
                if(!saveLocation.endsWith(".txt"))
                    saveLocation = saveLocation + ".txt";

                FileOutputStream out; // declare a file output object
                PrintStream p; // declare a print stream object

                try {
                    // Create a new file output stream
                    //  connected to "saveLocation" path
                    out = new FileOutputStream(saveLocation);

                    // Connect print stream to the output stream
                    p = new PrintStream(out);

                    // Write profile information to file
                    p.println (readUsername);
                    p.println (readName);
                    p.println (readEmail);
                    p.println (readPhone);
                    p.println (readWebsite);
                    p.println (readAboutMe);
                    p.println (readVisible);

                    p.close();
                }
                catch (Exception e)
                {
                    System.err.println ("Unable to write to file:\n\t" + saveLocation + "!");
                }
            }
        }
    }//GEN-LAST:event_exportProfileActionPerformed

    
/********************************************************************************
  Method: newProfileActionPerformed
  Description: Allows a user to creat a new profile
  Parameters: evt
  Used by: ProfileManager.java
  Uses: CreatProfile.java
********************************************************************************/
    private void newProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProfileActionPerformed
            // Show "Create New Profile" window to create a new profile
            CreateProfile createProfile;
            createProfile = new CreateProfile();
            //createProfile.tempMain = tempMain;
            createProfile.profileManager = this;

            createProfile.setVisible(true);
    }//GEN-LAST:event_newProfileActionPerformed
    
    
/********************************************************************************
  Method: doesProfileExist
  Description: Checks to see if a profile already exists (already loaded into
               D20 Chat - created or imported on the local machine)
  Parameters: profile
  Used by: NONE
  Uses: NONE
********************************************************************************/
    private boolean doesProfileExist(String profile) {
        // Setup to check if new profile already exists
            boolean profileAdded = false;
        
        // Check if profile (username) is already added
        // Create a buffer for our file to read into
        try {
            BufferedReader bin = new BufferedReader(new FileReader(profilePath));
      
            String line = bin.readLine();
            while (line != null) {
                // Check if currently read in profile is same as
                //  currently added profile
                if (line.compareTo(profile) == 0)
                    profileAdded = true;

                // Read in next profile
                line = bin.readLine();
            }
        } catch (Exception e) {
            System.err.println (e.getMessage());
        }
        
        return profileAdded;
    }

    
/**
     * Adds a profile to the jList in the profile manager form.
     * @param profileName Name of the profile to be added.
     */
    public void addProfile(String profileName) {
        try {
            // Add created profile to profileListing file
            //  (to keep track of all created profiles)
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
        
            // Check if profile (username) is already added
            // Create a buffer for our file to read into
            BufferedReader bin = new BufferedReader(new FileReader(profilePath));
            
            // Setup to check if new profile already exists
            boolean profileAdded = false;            
            String line = bin.readLine();
            while (line != null) {
                // Check if currently read in profile is same as
                //  currently added profile
                if (line.compareTo(profileName) == 0)
                    profileAdded = true;
                
                // Read in next profile
                line = bin.readLine();
            }
            
            // Append new profile if profile is NOT currently in list
            // If profile does already exists then just leave list alone
            //  (it's already in there so no need to add it or remove it)
            if (!profileAdded) {
                // Create a new file output stream connected
                //  to "profilePath" path
                out = new FileOutputStream(profilePath, true);

                // Connect print stream to the output stream
                p = new PrintStream(out);

                // Write profile information to file
                p.println (profileName);

                p.close();
                
                // Read in profile(s) already in pList (
                DefaultListModel listModel = new DefaultListModel();
                for (int i=0; i<pList.getModel().getSize(); i++)
                    listModel.addElement(pList.getModel().getElementAt(i).toString());
                
                // Add profile to temporary list listModel
                listModel.addElement(profileName);

                // Make jList a single selection jList and list of
                //  profiles to profileList scrollpane
                pList = new JList(listModel);
                pList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                this.profileList.setViewportView(pList);
            }
            
            // Either profile has been found or added
            // Done using file, so close it
            bin.close();
        }
        catch (Exception e)
        {
            System.err.println (e.getMessage());
        }
    }
    
    
/**
     * Returns the selected profile in the profile manager jList.
     * @return username of the selected profile.
     */
    public String getSelectedProfile() {
        // Get the index of the selected profile
        int selectedIndex = pList.getSelectedIndex();

        // Get the selected profile using the index
        Object selectedProfile = pList.getModel().getElementAt(selectedIndex);
        
        // Get the profile name
        String username = selectedProfile.toString();
        
        return username;
    }
    
    
/**
     * Indicates that the selected profile is being used (for user's sake).
     *  Used by: useProfileActionPerformed
     */
    private void indicateUsedProfile() {
        // Get selected profile and set it's font to bold
        int selectedIndex = pList.getSelectedIndex();
        
        Object selectedProfile = pList.getModel().getElementAt(selectedIndex);
        
        String userName = selectedProfile.toString();
        String profileName = userName;
        
        userName = userName + "   [LOADED]";
        
        // Read in profile(s) already in pList (to check for profile to remove)
        DefaultListModel listModel = new DefaultListModel();
        for (int i=0; i<pList.getModel().getSize(); i++)
            listModel.addElement(pList.getModel().getElementAt(i).toString());
        
        // Check in listModel for the profile to remove
        for (int i=0; i<listModel.getSize(); i++) {
            // Check profileName against every profile in pList
            // Remove if found match
            if (listModel.getElementAt(i).toString().compareTo(profileName) == 0)
                listModel.remove(i);
        }
        
        // Add username indicating that it's loaded
        listModel.addElement(userName);
        
        // Make jList a single selection jList and add list of
        //  profiles (with profile removed) to profileList scrollpane
        pList = new JList(listModel);
        pList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.profileList.setViewportView(pList);
    }
    
    
/**
     * Removes a profile from the profile manager jList and profileList file.
     * @param profileName name of the profile to be removed.
     */
    public void removeProfile(String profileName) {
        // Remove profileName from pList
        // Read in profile(s) already in pList (to check for profile to remove)
        DefaultListModel listModel = new DefaultListModel();
        for (int i=0; i<pList.getModel().getSize(); i++)
            listModel.addElement(pList.getModel().getElementAt(i).toString());
        
        // Check in listModel for the profile to remove
        for (int i=0; i<listModel.getSize(); i++) {
            // Check profileName against every profile in pList
            // Remove if found match
            if (listModel.getElementAt(i).toString().compareTo(profileName) == 0)
                listModel.remove(i);
        }
        
        // Delete the profile's file
        String oldFile = profileDir + profileName + ".txt";
        boolean success = (new File(oldFile)).delete();
        if (!success) // File unsuccessfully deleted
            System.out.println("File " + oldFile + " was not deleted!");
        else
            System.out.println("File " + oldFile + " was deleted!");
        
        // Make jList a single selection jList and add list of
        //  profiles (with profile removed) to profileList scrollpane
        pList = new JList(listModel);
        pList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.profileList.setViewportView(pList);
        
        // Now remove profile from profile listing file
        try {
            // Have new list of profiles WITHOUT the "removed" profile
            // Now write out new list of profiles to file
            
            // Create a new file output stream connected
            //  to "profilePath" path
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
            
            out = new FileOutputStream(profilePath);

            // Connect print stream to the output stream
            p = new PrintStream(out);

            // Write profiles to file (from pList jList - since it's updated)
            for (int i=0; i<pList.getModel().getSize(); i++) {
                // Check profileName against every profile in pList
                // Remove if found match
                p.println(pList.getModel().getElementAt(i).toString());
            }

            p.close(); 
        } catch (Exception e) {
            System.err.println (e.getMessage());
        }
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JButton deleteProfile;
    private javax.swing.JButton editProfile;
    private javax.swing.JButton exportProfile;
    private javax.swing.JButton importProfile;
    private javax.swing.JLabel lblExplanation;
    private javax.swing.JCheckBox loadDefault;
    private javax.swing.JButton newProfile;
    private javax.swing.JScrollPane profileList;
    private javax.swing.JButton setAsDefault;
    private javax.swing.JButton useProfile;
    // End of variables declaration//GEN-END:variables
    
}
